package master

import (
	"GoCrontab/crontab/common"
	"context"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"time"
)

type logManager struct {
	client          *mongo.Client
	mongoCollection *mongo.Collection
}

func (manager *logManager) ListLog(name string, skip *int64, limit *int64) (logArr []*common.JobLog, err error) {

	var (
		filter      *common.JobLogFilter
		sort        *common.JobLogSortByStartTime
		optionField *options.FindOptions
		cursor      *mongo.Cursor
		jobLog      *common.JobLog
	)
	logArr = make([]*common.JobLog, 0)

	filter = &common.JobLogFilter{JobName: name}

	//{startTime ：-1}//拼接mongo的参数
	optionField = &options.FindOptions{
		Sort:  sort,
		Skip:  skip,
		Limit: limit,
	}

	if cursor, err = manager.mongoCollection.Find(context.TODO(), filter, optionField); err != nil {
		return
	}
	defer cursor.Close(context.TODO())
	for cursor.Next(context.TODO()) {
		jobLog = &common.JobLog{}

		if err = cursor.Decode(jobLog); err != nil {
			continue //有日志无法解析，忽略。。
			return
		}
		logArr = append(logArr, jobLog)
	}
	return
}

var (
	GlobalLogManager *logManager
)

func InitLogManager() (err error) {

	var (
		client       *mongo.Client
		clientOpt    *options.ClientOptions
		timeOutMongo time.Duration
	)

	timeOutMongo = time.Duration(GlobalConfig.MondbConnectTimeOut) * time.Second
	clientOpt = &options.ClientOptions{
		ConnectTimeout: &timeOutMongo,
		Hosts:          []string{GlobalConfig.MondbUrl},
	}
	if client, err = mongo.Connect(context.TODO(), clientOpt); err != nil {
		return
	}
	GlobalLogManager = &logManager{
		client:          client,
		mongoCollection: client.Database(GlobalConfig.JobLogDBName).Collection(GlobalConfig.JobLogCollectionName),
	}
	return
}
